#include "purchaseorderlistdialog.h"
#include "ui_purchaseorderlistdialog.h"
#include "purchaseorderdialog.h"
#include "fulfillmentdialog.h"

#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>
#include <QWidget>
#include <QPushButton>
#include <QHBoxLayout>
#include <QDate>

PurchaseOrderListDialog::PurchaseOrderListDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::PurchaseOrderListDialog)
    , orderModel(new QSqlQueryModel(this))
{
    ui->setupUi(this);

    setWindowTitle("采购订单管理");

    //设置表格
    setupTable();

    //连接按钮信号
    connect(ui->btnRefresh, &QPushButton::clicked, this,&PurchaseOrderListDialog::refreshOrderList);
    connect(ui->btnAddNew, &QPushButton::clicked, this, &PurchaseOrderListDialog::onAddNewOrderClicked);

    //加载初始数据
    refreshOrderList();
}

PurchaseOrderListDialog::~PurchaseOrderListDialog()
{
    delete ui;
    delete orderModel;
}

void PurchaseOrderListDialog::on_buttonBox_accepted()
{
    //发送关闭信号
    emit poListDialogClosed();

    //关闭对话框并返回accepted状态
    accept();
}


void PurchaseOrderListDialog::on_buttonBox_rejected()
{
    //发送关闭信号
    emit poListDialogClosed();

    //关闭对话框并返回rejected状态
    reject();
}

void PurchaseOrderListDialog::refreshOrderList()
{
    //执行查询获得采购订单列表
    QSqlQuery query;
    query.prepare("SELECT "
                  "po.po_id AS `采购订单编号`, "
                  "po.order_date AS `下单日期`, "
                  "po.delivery_terms AS `交货条款`, "
                  "po.total_amount AS `订单总额`, "
                  "po.order_status AS `订单状态`, "
                  "s.name AS `供应商`, "
                  "NULL AS `操作` "
                  "FROM PurchaseOrder po "
                  "JOIN Supplier s ON po.supplier_id = s.supplier_id "
                  "ORDER BY po.order_date DESC");
    if(!query.exec())
    {
        QMessageBox::critical(this, "数据库错误", "加载采购订单失败："+query.lastError().text());
        return;
    }

    //设置模型数据
    orderModel->setQuery(std::move(query));

    //添加操作列按钮
    for (int row = 0; row < orderModel->rowCount(); row++)
    {
        addActionButtons(row);
    }
}

void PurchaseOrderListDialog::onViewDetailsClicked()
{
    QPushButton *button =qobject_cast<QPushButton*>(sender());
    if (!button) return;
    //获取按钮关联的行号
    int row = button->property("row").toInt();
    //从模型中获取订单ID
    int poId = orderModel->index(row, 0).data().toInt();

    //打开订单详情对话框
    PurchaseOrderDialog dlg(this);
    dlg.setOrderId(poId);
    dlg.exec();
}

void PurchaseOrderListDialog::onEditFulfillmentClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    int row = button->property("row").toInt();
    int poId = orderModel->index(row, 0).data().toInt();

    //打开履约编辑框
    FulfillmentDialog dlg(this);
    dlg.setOrderId(poId);

    if (dlg.exec() == QDialog::Accepted)
    {
        refreshOrderList();
    }
}

void PurchaseOrderListDialog::onDeleteOrderClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    int row = button->property("row").toInt();
    int poId = orderModel->index(row, 0).data().toInt();

    QString orderCode = orderModel->index(row, 0).data().toString();
    QString supplier = orderModel->index(row, 5).data().toString();

    //确认删除
    if (QMessageBox::question(this, "确认删除", QString("确定要删除采购订单 #%1 (供应商： %2)吗？\n此操作不可撤回").arg(orderCode).arg(supplier),
                                QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
    {
        return;
    }

    //执行删除操作
    QSqlDatabase::database().transaction();

    try
    {
        //先删去关联的明细
        QSqlQuery detailQuery;
        detailQuery.prepare("DELETE FROM PurchaseOrderDetail WHERE po_id = :poId");
        detailQuery.bindValue(":poId", poId);
        if (!detailQuery.exec())
        {
            throw std::runtime_error("删除采购订单明细错误：" + detailQuery.lastError().text().toStdString());
        }

        //删除履约记录
        QSqlQuery fulfillmentQuery;
        fulfillmentQuery.prepare("DELETE FROM PurchaseFulfillment WHERE po_id = :poId");
        fulfillmentQuery.bindValue(":poId", poId);
        if (!fulfillmentQuery.exec())
        {
            throw std::runtime_error("删除履约记录失败" + fulfillmentQuery.lastError().text().toStdString());
        }

        //最后删除订单
        QSqlQuery orderQuery;
        orderQuery.prepare("DELETE FROM PurchaseOrder WHERE po_id = :poId");
        orderQuery.bindValue(":poId", poId);
        if (!orderQuery.exec())
        {
            throw std::runtime_error("删除采购订单失败" + orderQuery.lastError().text().toStdString());
        }

        QSqlDatabase::database().commit();

        //刷新列表
        refreshOrderList();

        QMessageBox::information(this, "成功", "采购订单已删除");
    }
    catch(const std::exception &error)
    {
        //滚回事务
        QSqlDatabase::database().rollback();

        QMessageBox::critical(this, "数据库错误", error.what());
    }


}

void PurchaseOrderListDialog::onAddNewOrderClicked()
{
    //创建采购订单对话框
    PurchaseOrderDialog dlg(this);
    if (dlg.exec() == QDialog::Accepted)
    {
        //刷新列表
        refreshOrderList();
    }
}

void PurchaseOrderListDialog::closeEvent(QCloseEvent *event)
{
    //发送关闭信号
    emit poListDialogClosed();
    //接受关闭事件
    event->accept();
}

void PurchaseOrderListDialog::setupTable()
{
    // 设置表格模型
    ui->tblOrders->setModel(orderModel);
    ui->tblOrders->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tblOrders->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tblOrders->horizontalHeader()->setStretchLastSection(true);
    ui->tblOrders->verticalHeader()->setVisible(false);
    ui->tblOrders->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 设置列宽 - 添加操作列
    ui->tblOrders->setColumnWidth(0, 60);  // 订单编号
    ui->tblOrders->setColumnWidth(1, 100);  // 下单日期
    ui->tblOrders->setColumnWidth(2, 150);  // 交货条款
    ui->tblOrders->setColumnWidth(3, 60);  // 订单总额
    ui->tblOrders->setColumnWidth(4, 100);  // 订单状态
    ui->tblOrders->setColumnWidth(5, 50);  // 供应商
    ui->tblOrders->setColumnWidth(6, 400);  // 操作列
}

void PurchaseOrderListDialog::addActionButtons(int row)
{
    //创建容器控件
    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout(widget);
    layout->setContentsMargins(5, 2, 5, 2);
    layout->setSpacing(5);

    // 查看明细按钮
    QPushButton *btnView = new QPushButton("查看明细");
    btnView->setProperty("row", row);
    connect(btnView, &QPushButton::clicked, this, &PurchaseOrderListDialog::onViewDetailsClicked);

    // 编辑履约按钮
    QPushButton *btnEdit = new QPushButton("编辑履约");
    btnEdit->setProperty("row", row);
    connect(btnEdit, &QPushButton::clicked, this, &PurchaseOrderListDialog::onEditFulfillmentClicked);

    // 删除订单按钮
    QPushButton *btnDelete = new QPushButton("删除");
    btnDelete->setProperty("row", row);
    connect(btnDelete, &QPushButton::clicked, this, &PurchaseOrderListDialog::onDeleteOrderClicked);

    // 添加到布局
    layout->addWidget(btnView);
    layout->addWidget(btnEdit);
    layout->addWidget(btnDelete);

    // 设置容器到表格
    ui->tblOrders->setIndexWidget(
        orderModel->index(row, orderModel->columnCount()-1),
        widget
        );
}

